var db = new DBWrapper("tablecopy", 1, {
  onupgradeneeded: (e) => {
    const db = e.target.result;
    const objStore = db.createObjectStore("tables", {
      autoIncrement: true,
      keyPath: "id",
    });
    objStore.createIndex("table", "table", { unique: !1 });
    objStore.createIndex("rowtag", "rowtag", { unique: 1 });
  },
});

const dealrows = function (arr) {
  // #TODO
  arr.forEach((data) => {
    const d = {
      table: data.tag,
      rowtag: $.md5(data.tag + $(data.row).context.outerHTML),
      row: $(data.row).context.outerHTML,
    };
    db.add("tables", d);
  });
};

//消息队列
const queue = new AsyncMessageQueue();

const addRow = function (tag, row) {
  queue.enqueue({ tag: tag, row: row });
  return;
  let tables = JSON.parse(localStorage.getItem("_table_copy_"));
  tables.forEach((table) => {
    if (table.tag == tag) {
      let rowtag = $.md5($(row).context.outerHTML);
      if (table.rowtags.includes(rowtag)) {
        return;
      } else {
        table.rowtags.push(rowtag);
        table.rows.push($(row).context.outerHTML);
        table.rowcount++;
        localStorage.setItem("_table_copy_", JSON.stringify(tables));
      }
    }
  });
};

const addRowTarget = function (tag, row) {
  queue.enqueue({ tag: tag, row: row });
  return;
  let tables = JSON.parse(localStorage.getItem("_table_copy_"));
  tables.forEach((table) => {
    if (table.tag === tag) {
      let rowtag = $.md5($(row).context.outerHTML);
      if (!table.rowtags.includes(rowtag)) {
        table.rowtags.push(rowtag);
        table.rows.push($(row).context.outerHTML);
        table.rowcount++;
        localStorage.setItem("_table_copy_", JSON.stringify(tables));
      }
    }
  });
};

const findTable = function () {
  let tables = JSON.parse(localStorage.getItem("_table_copy_"));
  $("table").each(function () {
    let table = {};
    table.head = $(this).find("tr:first").text();
    table.tag = $.md5($(this).html());
    table.rowcount = 0;
    table.rows = [];
    table.rowtags = [];
    let rows = $(this).find("tr");
    rows.each(function () {
      const d = {
        table: table.tag,
        rowtag: $.md5(table.tag + $(this).context.outerHTML),
        row: $(this).context.outerHTML,
      };
      db.add("tables", d);
    });
    tables.push(table);

    //监听表格变化

    // 目标元素
    const targetElement = this;

    // 创建一个MutationObserver实例
    const observer = new MutationObserver((mutations) => {
      let tag = table.tag;
      mutations.forEach((mutation) => {
        if (mutation.type === "childList") {
          mutation.addedNodes.forEach((addedNode) => {
            if (addedNode.nodeName === "TR") {
              addRow(tag, addedNode);
            }
          });
        }
      });
    });

    // 配置观察器
    const config = {
      childList: true,
    };

    // 启动观察器
    observer.observe(targetElement, config);
    // console.log(observer);
  });
  localStorage.setItem("_table_copy_", JSON.stringify(tables));
};

const observeDocument = function () {
  // 创建一个MutationObserver实例并提供回调函数
  const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
      if (mutation.type === "childList") {
        if (mutation.target.id === "_table_copy_Container") return;
        mutation.addedNodes.forEach((addedNode) => {
          if (addedNode.nodeName === "TABLE") {
            if (!addedNode.hasAttribute("data-table-processed")) {
              addTable(addedNode);
              addedNode.setAttribute("data-table-processed", "true");
            }
          }
          if (addedNode.tagName === "DIV") {
            addedNode.querySelectorAll("table").forEach(function (table) {
              if (!table.hasAttribute("data-table-processed")) {
                addTable(table);
                table.setAttribute("data-table-processed", "true");
              }
            });
          }
        });
      }
    });
  });

  // 配置选项
  const config = {
    childList: true, // 监听子节点的变化
    subtree: true, // 监听整个DOM树的变化
  };

  // 选择需要观察的节点（这里选择document，即整个文档）
  const targetNode = document;

  // 以配置选项开始观察目标节点
  observer.observe(targetNode, config);
  // console.log(observer);
};

const addTable = function (tableNode) {
  let tables = JSON.parse(localStorage.getItem("_table_copy_"));
  let table = {};
  table.head = $(tableNode).find("tr:first").text();
  table.tag = $.md5($(tableNode).context.outerHTML);
  const hasTag = tables.some(function (obj) {
    return obj.tag === table.tag;
  });
  if (hasTag) return;
  table.rowcount = 0;
  table.rows = [];
  table.rowtags = [];
  let rows = $(tableNode).find("tr");
  rows.each(function () {
    // table.rowcount++;
    // table.rows.push($(this).context.outerHTML);
    // table.rowtags.push($.md5($(this).context.outerHTML));
    const d = {
      table: table.tag,
      rowtag: $.md5(table.tag + $(this).context.outerHTML),
      row: $(this).context.outerHTML,
    };
    db.add("tables", d);
  });
  tables.push(table);
  // console.log(table);
  localStorage.setItem("_table_copy_", JSON.stringify(tables));

  //监听表格变化
  $(tableNode).on("DOMNodeInserted", function (mutation) {
    let tag = table.tag;
    if (mutation.target.tagName === "TR") {
      addRowTarget(tag, mutation.target);
    }
  });
};

function tableToTextWithTabs(table) {
  let text = "";
  const rows = $(table).find("tr");
  rows.each(function () {
    $(this)
      .find("td,th")
      .each(function () {
        text += $(this).text() + "\t";
        if ($(this).attr("colspan")) {
          const colspan = Number($(this).attr("colspan"));
          if (colspan - 1 > 0) {
            const tabs = "\t".repeat(colspan - 1);
            text += tabs;
          }
        }
      });
    text += "\n";
  });
  return text;
}

function htmlToExcel(htmlString) {
  // 创建一个新的DOM对象以解析HTML
  $("#_table_copy_table").html(htmlString);
  const excelString = tableToTextWithTabs("#_table_copy_table");
  $("#_table_copy_table").html("");
  return excelString;
}

$(document).ready(function () {
  if (self == top) {
    localStorage.setItem("_table_copy_", JSON.stringify([]));
    db.clear("tables");
    //主窗口添加按钮
    addball();
  }
  setInterval(() => {
    queue.run(dealrows);
  }, 1000);
  //监听动态表格
  observeDocument();
  //查找表格
  findTable();
});
